import vue from 'vue'
import Vuex from 'vuex'
import router,{resetRouter} from '../router/IndexPage';
import createPersistedState from 'vuex-persistedstate'
import axios from "axios";
vue.use(Vuex)

function addNewRoute(menuList) {
    console.log(menuList)
    let routes = router.options.routes
    console.log(routes)
    routes.forEach(routeItem=>{
        if (routeItem.path=="/IndexPage"){
            menuList.forEach(menu=>{
                let childRoute = {
                    path:'/'+menu.menuclick,
                    name:menu.menuname,
                    meta:{
                        title:menu.menuname
                    },
                    component:()=>import('../components/'+menu.menucomponent)
                }
                routeItem.children.push(childRoute)
            })
        }
    })
    routes.forEach(route => {
        router.addRoute(route)
    })

}
export default new Vuex.Store({
    state: {//存储数据
        menu: [],
        user: JSON.parse(sessionStorage.getItem('CurUser')),
        knowledge: JSON.parse(sessionStorage.getItem('CurUser')) || null,
    },
    getters: {//获取state中的数据时进行一些计算或过滤处理
        getMenu(state){
            return state.menu
        }
    },
    plugins:[createPersistedState()],
    mutations: {//同步更改状态
        setMenu(state, menuList){ //依赖注入state
            state.menu = menuList
            addNewRoute(menuList)
        },
        setRouter(state, menuList){ //依赖注入state
            addNewRoute(menuList)
        },
        setUser(state, user) {
            state.user = user;
            sessionStorage.setItem('CurUser', JSON.stringify(user)); // 保存到 sessionStorage
        },
        clearUser(state) {
            state.user = null
            sessionStorage.removeItem('CurUser'); // 清除 sessionStorage
        },
        updateUser(state, payload) {
            state.user = { ...state.user, ...payload };
            sessionStorage.setItem('CurUser', JSON.stringify(state.user))
        }
    },
    actions: {
        login({ commit }, user) {
            commit('setUser', user);
            sessionStorage.setItem("CurUser", JSON.stringify(user));
        },
        logout({ commit }) {
            commit('clearUser');
            /*sessionStorage.removeItem('CurUser');
            localStorage.removeItem('其他可能存储的键'); //移除用户信息*/
            /*return axios.post('/user/logout') // 改为直接使用导入的 axios
                .then(()=> {
                    console.log('登出成功');
                })
                .catch(error => {
                    console.error('登出请求失败:', error);
                });*/
        }
    },
    /*modules: {
        //模块化状态管理
    }*/
})